package com.enjoy.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class NioClientHandler implements Runnable {
    private final String host;
    private final int port;
    private final boolean started;
    private Selector selector;
    private SocketChannel socketChannel;

    public NioClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            /*创建选择器的实例*/
            selector = Selector.open();
            /*创建通道实例*/
            socketChannel = SocketChannel.open();
            /*设置通道为非阻塞模式*/
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        started = true;

    }

    @Override
    public void run() {
        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (started) {
            try {
                /*获取当前有哪些事件*/
                selector.select(1000);
                /*获取事件的集合*/
                final Set<SelectionKey> selectionKeys = selector.selectedKeys();
                final Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    final SelectionKey key = iterator.next();
                    iterator.remove();
                    handleInput(key);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 有事件的情况下调用
    private void handleInput(SelectionKey key) throws IOException {

        if (key.isValid()) {
            /*获取关心当前事件的channel*/
            SocketChannel sc = (SocketChannel) key.channel();
            /*处理新接入的客户端请求*/
            if (key.isConnectable()) {
                if (sc.finishConnect()) {
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else {
                    System.exit(1);
                }
            }
            /*处理对端发送的数据*/
            if (key.isReadable()) {
                final ByteBuffer buffer = ByteBuffer.allocate(1024);
                /*从通道里读数据*/
                final int readBuffer = sc.read(buffer);
                if (readBuffer > 0) {
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String message = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("客户端接收消息:" + message);
                }
                /*链路已经关闭*/
                else if (readBuffer < 0) {
                    key.cancel();
                    sc.close();
                }

            }
        }
    }

    private void doConnect() throws IOException {
        /*非阻塞的连接*/
        // 如果此通道处于非阻塞模式并且正在进行连接操作返回false
        if (socketChannel.connect(new InetSocketAddress(this.host, this.port))) {
            socketChannel.register(selector, SelectionKey.OP_READ);
        } else {
            // 注册连接事件
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    public void sendMsg(String msg) throws IOException {
        doWrite(socketChannel, msg);
    }

    private void doWrite(SocketChannel socketChannel, String msg) throws IOException {
        final byte[] bytes = msg.getBytes();
        final ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        socketChannel.write(buffer);
    }
}
